//
//
///

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, Image, ListView, StyleSheet, Text, View} from 'react-native';
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation from "../../custom/Navigation";
import ViewUtils from "../../utils/ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import I18n from "../../res/language/i18n";
import ModalListUtils from "../../utils/ModalListUtils";
import IparNetwork, {SERVER_TYPE} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";
import IparInput from "../../custom/IparInput";


let clickTypes = {sendVerCode: 'sendVerCode', submit: 'submit'};

let ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
});
export default class FindPasswordPage extends Component {


    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();
        this.userPhoneNumber = '';
        this.verificationCode = '';
        this.userPassWord = '';
        this.countryData = this.props.countryData || [];
        this.userId;
        this.state = {
            countryIndex: -1,
            countryCode: I18n.t('default.countryCode'),
            modalVisible: false,
            verificationTimer: I18n.t('default.sendVerCode'),
        }
    }


    componentDidMount() {
        if (this.countryData.length <= 0) {
            this.getCountryData();
        }
    }

    /**
     * 获取各个国家的数据..
     */
    getCountryData() {
        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', '')
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result && result.length >= 0) {
                    this.countryData = result;
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            })
    }

    /**
     * 验证-手机号
     */
    checkUserKey() {
        this.showLoading(true);
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'checkUserKey?', 'keywords=' + this.userPhoneNumber)
            .then((result) => {
                if (result.code === 200) {//用户已存在
                    this.userId = result.data.main_user_id;
                    this.sendVerificationCode();
                } else {//用户未存在
                    DeviceEventEmitter.emit('toast', I18n.t('default.userNotExist'));
                    this.showLoading(false);
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });
    }


    /**
     * 发送验证码
     */
    sendVerificationCode() {

        let countryDatum = this.countryData[this.state.countryIndex];
        if (!countryDatum) {
            this.props.navigator.pop();
            return;
        }

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'sms?',
            'phone=' + this.userPhoneNumber + '&type=updatePassword&country=' + countryDatum.area_code)
            .then((result) => {
                this.showLoading(false);
                if (result.code === 200) {
                    this.countTime();
                    console.log(result)
                    DeviceEventEmitter.emit('toast', I18n.t('toast.sendVerCodeSuccess'));
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });

    }


    /**
     * 加载中效果
     */
    showLoading(visible) {
        if (visible) {
            CommonUtils.showLoading();
        } else {
            CommonUtils.dismissLoading();
        }
    }


    /**
     * 发送验证码的效果（btn 的 文字（59...））
     */
    countTime() {
        this._index = 60;
        this._timer = setInterval(() => {
            this.setState({verificationTimer: this._index-- + ' s'});
            if (this.state.verificationTimer <= 0 + ' s') {
                this._timer && clearInterval(this._timer);
                this.setState({verificationTimer: I18n.t('toast.againGetCode')});
            }
        }, 1000);
    }

    /**
     * finish page的时候
     */
    componentWillUnmount() {
        this._timer && clearInterval(this._timer);
    }

    /**
     * 点击
     * @param type
     */
    onClick(type) {
        switch (type) {
            case clickTypes.sendVerCode:

                if (this.state.countryCode === I18n.t('default.countryCode')) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.countryCode'));
                    return;
                }

                if (!this.userPhoneNumber.trim()) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.enterPhoneNum'));
                    return;
                }

                if (this._index > 0) {
                    return;
                }

                this.checkUserKey();

                break;
            case clickTypes.submit:
                if (this.state.countryCode === I18n.t('default.countryCode')) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.countryCode'));
                    return;
                }

                if (!this.userPhoneNumber.trim()) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.enterPhoneNum'));
                    return;
                }

                if (!this.verificationCode.trim()) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.enterPass'));
                    return;
                }
                if (!this.userPassWord.trim()) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.enterPass'));
                    return;
                }

                if (!CommonUtils.isPassword(this.userPassWord)) {
                    DeviceEventEmitter.emit('toast', I18n.t('toast.isNotPassword'));
                    return;
                }


                this.submit();
                break;
        }
    }


    /**
     * 体检数据
     */
    submit() {


        this.showLoading(true);
        let formData = new FormData();
        formData.append('area_code', this.state.countryCode);
        formData.append('mobile', this.userPhoneNumber);
        formData.append('code', this.verificationCode);
        formData.append('user_pass', this.userPassWord);

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'findPassword', formData)
            .then((result) => {
                this.showLoading(false);
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.pop();
                } else if (result.code === 444) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.verCodeError'));
                } else {
                    console.log('FindPasswordPage---submit--fail: ', result);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log('FindPasswordPage---submit--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            })

    }


    /**
     * modal 的item click
     */
    onModalItemClick(index, text) {
        this.setState({
            countryIndex: index,
            countryCode: text,
            modalVisible: false,
        })
    }


    render() {


        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    titleImage={require('../../res/images/ic_ipar_logo.png')}
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}/>


                <KeyboardAwareScrollView
                >
                    <View style={{padding: 16}}>
                        {ViewUtils.getTitleView(I18n.t('default.findPass'), I18n.t('default.resetPassword'))}
                        <View style={[StyleUtils.justifySpace]}>
                            {ViewUtils.getButtunMenu(this.state.countryCode, () => this.setState({
                                modalVisible: true
                            }), [StyleUtils.marginTop, {width: '33%'}])}

                            <IparInput
                                keyboardType={'number-pad'}
                                style={{width: '64%'}}
                                onChangeText={(text) => this.userPhoneNumber = text}
                                placeholder={I18n.t('default.enterPhoneNum')}/>
                        </View>


                        <View style={[StyleUtils.center, StyleUtils.justifySpace, StyleUtils.marginTop]}>

                            <IparInput
                                keyboardType={'number-pad'}
                                style={{
                                    marginTop: 0,
                                    width: '64%'
                                }}
                                onChangeText={(test) => this.verificationCode = test}
                                placeholder={I18n.t('toast.enterVerification')}/>

                            {ViewUtils.getButton(this.state.verificationTimer, () => this.onClick(clickTypes.sendVerCode), {width: '33%'}, {fontSize: 14})}

                        </View>

                        <IparInput
                            isPassword={true}
                            onChangeText={(text) => this.userPassWord = text}
                            placeholder={I18n.t('default.interNewPass')}/>

                        {ViewUtils.getButton(I18n.t('default.submit'), () => this.onClick(clickTypes.submit), StyleUtils.marginTop)}

                    </View>
                </KeyboardAwareScrollView>


                <ModalListUtils
                    close={() => this.setState({
                        modalVisible: false,
                    })}
                    onPress={(index, text) => this.onModalItemClick(index, text)}
                    visible={this.state.modalVisible}
                    dataSource={ds.cloneWithRows(this.countryData)}
                    dataParam={'area_code'}
                />


            </View>
        );
    }
}




